 
//imports
import { homeData, articleCollect,Transpond} from '../../../api/eapi.js';
import util from '../../../utils/util.js';
import app from '../../../utils/app.js';
let WxParse = require("../../../wxParse/wxParse.js")

/**
 * Page
 */
Page({
  data: {
    articleId: false,
    content:null ,
    animation:'',
    template: {
      wine: 'template-wine'
    },
    articles:'',
    video:{
      play:true,
      src:''
    },
    homeData:''
  },

  videoplay: function(e) {
    if (e.currentTarget.dataset.type=='true'){
      return 
    };
    
    if(this.data.video.play){
      let src = e.currentTarget.dataset.imgsrc;
      this.setData({
        video: {
          play: false,
          src: src
        }
      }) ;
      this.videocontent.play() ;
      this.setData({
      animation:this.animation.export()
    });
    }else{
  
    this.setData({
      video:{
        play:true,
        src:''
      }
    });
    this.videocontent.pause()   
   }
  },


  onLoad: function (options) {

   
    let ID=options.product;
    let _this=this;
    let body = {
      detail: true
    };
    homeData("article/" + ID, { data: body }).then(res => {

      _this.setData({
        content:res.data.data
      });
    
      homeData("article", {data:{column:res.data.data.column_id}}).then(es =>{
        let data = es.data.data.data;
        data.forEach(item =>{
          item.selected = item.user_has_collect ? true : false
        });
        let obj = { title: es.data.data.data[0].column_name,
                    homeData:es.data.data.data,
                    subtitle:true};
        _this.setData({
          articles:obj
        });
        console.log(obj)
      })

      let article = res.data.data.content;

      let productid = article.match(/{{drink:\d+}}/g); 
      if(productid){ 
       productid = productid.toString().match(/\d+/g);
       productid.map(function(es){
        article = article.replace(/{{drink:\d+}}/g, '<wine data='+es+'>AAAA</wine>');
      })
      }

      let data = WxParse.wxParse('article', 'html', article, _this, 0);

      let nodes = [];
      function lookup(node) {
        if (node.tag === 'wine') {
          nodes.push(node);
        }

        if (node.nodes) {
          for (let i = 0; i < node.nodes.length; i++) {
            lookup(node.nodes[i]);
          }
        }
        
      }

      lookup(data.article);

      function esss(res) {
       
          if (res.tag == 'wine') {
            homeData('drink/' + res.attr.data, {}).then(es => {
              res.nodes = es.data.data;
              _this.setData(data)
            })
            return 
          };
         
        if (res.nodes) {
          res.nodes.map(es =>{
            esss(es)
          })
         
        }
      };

       data.article.nodes.map(res => {
        esss(res)
      });

       this.setData(data);
    });
  
  },
  collection(e){
    console.log(this.data.content);

    let _this=this;
    if(e.currentTarget.dataset.coll == "true"){
      articleCollect.post({id:this.data.content.id}).then(res =>{
        _this.setData({'content.user_has_collect':'e'})
      })
    }else{
      articleCollect.delete({ ids: this.data.content.id}).then(res=>{
        _this.setData({'content.user_has_collect':null})
      })
    }
  },
  onReady:function(){
    let query=wx.createSelectorQuery();
    let html=query.select("drink_product");
    this.videocontent = wx.createVideoContext('videoplay');
    
  },
  onShow:function(){
    let animation=wx.createAnimation({
      duration: 400,
      timingFunction: '"linear"',
      delay: 0,
      transformOrigin: '"50% 50% 0"',
    });
    this.animation=animation;
    animation.scale(0.3,0.3).scale(1,1).step();
  
  },
  onAddCollection: function (e) {
    let id = e.target.dataset.id;
    let homeData = this.data.articles.homeData;
    wx.showToast({ icon: 'loading' });
    articleCollect.post({ id: id }).then(res => {
      homeData.forEach(item => {
        if (item.id === id) {
          item.selected = true;
        }
      })
      // 更新选中状态
      this.setData({
        'articles.homeData': homeData
      }, () => wx.showToast({ title: '收藏成功' }))
    }).catch(err => console.error(err));


  },
  onRemoveCollection: function (e) {
    let id = e.target.dataset.id;
    let homeData = this.data.articles.homeData;
    wx.showToast({ icon: 'loading' });
    articleCollect.delete({ ids: id }).then(res => {
      homeData.forEach(item => {
        if (item.id === id) {
          item.selected = false;
        }
      })
      // 更新选中状态
      this.setData({
        'articles.homeData': homeData
      }, () => wx.showToast({ title: '取消收藏成功' }))
    }).catch(err => console.error(err));
  },
  onShareAppMessage:function(res){
    if(res.from=='menu'){
      res['from']='button';
      res.target = {
        dataset: {
          type: `1,${this.data.content.id},${this.data.content.covers[0].imgSrv},${this.data.content.title}`
        }
      }
    }
    return Transpond(res)
  },
  onUnload: function () {
    let pages = getCurrentPages();
    if (pages[0].route.match(/QRcode/)) {
      wx.switchTab({
        url: '/pages/catalog/home/index'
      })
    }
  }
})
